/* eslint-disable radix */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-shadow */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-use-before-define */
/* eslint-disable react/no-string-refs */
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Spin, Collapse } from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BasicInfo from './Addinfo/BasicInfo';
import InvoiceInfo from './Addinfo/InvoiceInfo';
import MailingAddress from './Addinfo/Mailingaddress';
import BankInfo from './Addinfo/BankInfo';
import Contacts from './Addinfo/Contacts';

const { Panel } = Collapse;
@connect(({ supplier, loading }) => ({
  supplier,
  loading: loading.models.supplier,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKeyList: [],
      custAffixList: [],
      invoiceAffixList: [],
      btnloading: false,
    };
  }

  componentDidMount() {
    this.getDictList();
  }

  // 获取字典:
  // 当前页签CUST_TAB、发票类型MINI_INV_TYPE、纳税人类型、所属银行BANK_ID、性别GENDER、是否有小孩HAS_CHILD、
  getDictList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplier/queryDictItemsByCodes',
      payload: ['CUST_TAB', 'MINI_INV_TYPE', 'TAXPAYER_TYPE', 'BANK_ID', 'GENDER', 'HAS_CHILD'],
    });
  };

  // 切换折叠面板
  changePanel = key => {
    this.setState({ activeKeyList: key });
  };

  // 获取客户信息文件参数
  getFileInfo = custAffixList => {
    this.setState({ custAffixList });
  };

  // 获取增值税发票文件
  getAffixList = AffixListParams => {
    this.setState({ invoiceAffixList: AffixListParams });
  };

  // 取消
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplier/updateModalData',
      payload: {
        formFieldsValue: {},
        activeKey: '2',
        expandForm: false,
        pageData: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
    router.push('/salemanage/supplier/index?activeKey=2');
  };

  // 提交数据
  sumSubmit = e => {
    e.preventDefault();
    const { activeKeyList, custAffixList } = this.state;
    const { dispatch } = this.props;
    let custInfo = {};
    let isSubmit = true;
    let submitData = {};
    let suppInvoiceList = []; // 发票信息
    let suppMailAddrList = []; // 邮寄地址
    const suppBankAccountList = []; // 银行账户信息
    let suppContactList = []; // 联系人信息

    activeKeyList.forEach(key => {
      this.refs[key].validateFieldsAndScroll((err, values) => {
        if (!err) {
          switch (key) {
            case 'invoiceInfo':
              suppInvoiceList = getInvoiceArrayData(values);
              suppInvoiceList.map(item => {
                item.invoiceAffixList = this.state.invoiceAffixList;
              });
              break;
            case 'mailingAddressInfo':
              suppMailAddrList = getAddressArrayData(values);
              break;
            case 'bankInfo':
              for (const key in values) {
                if (values[key] && values[key].key) {
                  values[key] = values[key].key;
                } else {
                  values[key] = values[key] ? values[key] : '';
                }
              }
              suppBankAccountList.push(values);
              break;
            case 'contactsInfo':
              suppContactList = getContactsArrayData(values);
              break;
            default:
              break;
          }
        } else {
          isSubmit = false;
        }
      });
    });
    this.refs.basicInfo.validateFieldsAndScroll((err, values) => {
      // delete values.custAffixList
      if (!err) {
        custInfo = values;
        for (const key in values) {
          if (values[key] && values[key].key) {
            custInfo[key] = values[key].key;
          } else {
            custInfo[key] = values[key] ? values[key] : '';
          }
        }
        if (custAffixList.length) {
          custAffixList.map(f => {
            delete f.uid;
          });
        }
        submitData = {
          ...custInfo,
          suppInvoiceList,
          suppMailAddrList,
          suppBankAccountList,
          suppContactList,
        };
      } else {
        isSubmit = false;
      }
    });
    if (isSubmit) {
      this.setState({ btnloading: true });
      dispatch({
        type: 'supplier/addInsert',
        payload: submitData,
      }).then(res => {
        if (res.success) {
          this.setState({ custAffixList: [], invoiceAffixList: [] });
          message.success('新增成功', 2, () => {
            dispatch({
              type: 'supplier/updateModalData',
              payload: {
                formFieldsValue: {},
                activeKey: '2',
                expandForm: false,
                pageData: {
                  pagination: {
                    current: 1,
                    pageSize: 10,
                    total: 10,
                  },
                },
              },
            });
            router.push('/salemanage/supplier/index?activeKey=2');
            this.setState({
              btnloading: false,
            });
          });
        } else {
          message.warning(`${res.message || '新增失败！'}`);
        }
      });
    }
  };

  render() {
    const {
      supplier: { taxerTypeList, bankList, genderList, hasChildList },
      loading,
    } = this.props;
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <BasicInfo ref="basicInfo" />
          <Collapse
            style={{ marginBottom: 24 }}
            activeKey={this.state.activeKeyList}
            onChange={this.changePanel}
          >
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>发票信息</span>}
              key="invoiceInfo"
            >
              <InvoiceInfo
                ref="invoiceInfo"
                taxerTypeList={taxerTypeList}
                getAffixList={fileInfo => this.getAffixList(fileInfo)}
              />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>邮寄地址信息</span>}
              key="mailingAddressInfo"
            >
              <MailingAddress ref="mailingAddressInfo" />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>银行账户信息</span>}
              key="bankInfo"
            >
              <BankInfo ref="bankInfo" bankList={bankList} />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>联系人信息</span>}
              key="contactsInfo"
            >
              <Contacts ref="contactsInfo" genderList={genderList} hasChildList={hasChildList} />
            </Panel>
          </Collapse>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.sumSubmit} loading={this.state.btnloading}>
              提交
            </Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
// 组合新增的数据：发票，地址，联系人,成本中心
const getInvoiceArrayData = data => {
  const indexList = [];
  for (const key in data) {
    if (data.hasOwnProperty(key) && key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  }
  return indexList.map(i => ({
    vatCoprName: data[`vatCoprName_list_${i}`],
    invType: data[`taxerType_list_${i}`].key,
    taxerIdNo: data[`taxerIdNo_list_${i}`],
    openBank: data[`openBank_list_${i}`] || '',
    bankAcco: data[`bankAcco_list_${i}`] || '',
    invPhone: data[`invPhone_list_${i}`] || '',
    invArea: data[`invArea_list_${i}`] || '',
    remark: data[`remark_list_${i}`] || '',
  }));
};

const getAddressArrayData = data => {
  const indexList = [];
  for (const key in data) {
    if (data.hasOwnProperty(key) && key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  }
  return indexList.map(i => ({
    contPerName: data[`contPerName_list_${i}`],
    contPerPhone: data[`contPerPhone_list_${i}`],
    mailArea: data[`mailAreaName_list_${i}`],
    mailCounty: data[`mailArea_list_${i}`][data[`mailArea_list_${i}`].length - 1],
    mailAddr: data[`mailAddr_list_${i}`],
    remark: data[`remark_list_${i}`] || '',
  }));
};

const getContactsArrayData = data => {
  const indexList = [];
  for (const key in data) {
    if (data.hasOwnProperty(key) && key.indexOf('list_') > -1) {
      const index = parseInt(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  }
  return indexList.map(i => ({
    name: data[`name_list_${i}`],
    email: data[`email_list_${i}`],
    position: data[`position_list_${i}`],
    phoneNo: data[`phoneNo_list_${i}`],
    tel: data[`tel_list_${i}`] || '',
    remark: data[`remark_list_${i}`] || '',
  }));
};
export default BasicForm;
